package member.base.action;

import m.common.action.ActionRequest;
import m.common.action.Param;
import m.common.action.RequestMethod;
import m.common.model.util.*;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import member.base.model.MemberInfo;
import member.base.model.UserInfo;
import member.base.util.PowerUtil;

import java.util.Date;

@ActionRequest(name = "action/base/memberInfo",description = "会员")
public class MemberInfoAction extends BaseAction{

    @RequestMethod(description = "列表")
    public JSONMessage getList() throws Exception {
        ModelQueryList queryList=toQueryList(MemberInfo.class,"*","level.name","level.color","level.discount");
        queryList.addCondition(QueryCondition.eq("business.oid", PowerUtil.getBusiness().getOid()));
        boolean hasManage=PowerUtil.hasPower(UserInfo.PowerManage);
        String userOid=PowerUtil.getUser().getOid();
        if (!hasManage) {
            queryList.addFieldExpression("phoneNum",
            "if(#{inputUser.oid}='"+userOid+"',#{phoneNum},concat(left(#{phoneNum},3),'****',right(#{phoneNum},4)))");
        }
        return JSONMessage.success("查询成功").push("page",
            ModelQueryList.getModelPageInfo(queryList)
            .convertToNew(item->{
                JSONMessage json=item.toJson();
                String uOid=((MemberInfo)item).getInputUser().getOid();
                json.push("operable",hasManage||userOid.equals(uOid));
                return json;
            })
        );
    }
    @RequestMethod(description = "保存")
    public JSONMessage save(@Param("model") MemberInfo model) throws Exception {
        model.setBusiness(PowerUtil.verifyBusiness(model.getBusiness()));
        ModelQueryCheck.init(model)
            .checkNotNull("realName","姓名不能为空")
            .checkNotNull("phoneNum","手机号不能为空")
            .checkNotNull("level.oid","请选择级别")
            .doCheck(false,true);
        if(ObjectUtil.isEmptyOid(model)) {
            model.setBalance(0.0);
            model.setFreeze(0.0);
            model.setRealMoney(0.0);
            model.setGiveMoney(0.0);
            model.setPoint(0);
            model.setUseMoney(0.0);
            model.setOrderNum(0);
            model.setInputUser(PowerUtil.getUser());
            model.setInputStore(PowerUtil.getStore());
            model.setInputDate(new Date());
        }else{
            if (!PowerUtil.hasPower(UserInfo.PowerManage)) {
                ModelCheckUtil.equals(model, new String[]{"inputUser.oid"}, new Object[]{PowerUtil.getUser().getOid()}, "权限不足");
            }
        }
        ModelCheckUtil.checkUniqueCombine(model,new String[]{"business.oid","phoneNum"},"会员手机号已存在");
        ModelUpdateUtil.saveModel(model,"realName","phoneNum","level.oid","remark","status");
        return JSONMessage.success("保存成功");
    }
}
